//
//  SWNewWorkTool.swift
//  MYSwiftWeiBo
//
//  Created by shingwai chan on 16/2/28.
//  Copyright © 2016年 ChanShingWai. All rights reserved.
//

import UIKit
import AFNetworking

//自定义错误枚举
enum SWNetWorkToolError :Int {
    
    case AccssesTokenEmpty = -1 // AccssesToken没值
    case UidEmpty = -2 //uid
    case statusLoading = -3//正在加载微博
    
    var errorMessgaer: String {
    
        get{
            switch self {
            case AccssesTokenEmpty : return "AccssesToken没有值"
            case UidEmpty: return "Uid没有值"
            case statusLoading :return "微博正在加载"
            
            }
        }
    }
    //返回错误信息枚举方法
    func error() ->NSError {
        return NSError(domain: "wai.com", code: self.rawValue, userInfo: ["errorMessgaer" : errorMessgaer])
    }
}

class SWNetWorkTool: NSObject {

    let afnManger :AFHTTPSessionManager
    //单例
    static let sharedNetWorkTool :SWNetWorkTool = SWNetWorkTool()
    
    override init() {
        //基础站
        let baseURL = NSURL(string: "https://api.weibo.com/")
        afnManger = AFHTTPSessionManager(baseURL: baseURL)
        //增加支持xml
        afnManger.responseSerializer.acceptableContentTypes?.insert("text/plain")
        super.init()
    }
    
    //MARK:——————OAuth授权配置
    //appKey
    let client_id = "526599748"
    //授权回调网址
    let redirect_uri = "http://www.baidu.com/"
    //OAuth2的authorize接口
    let oAuth2URL = "https://api.weibo.com/oauth2/authorize"
    let client_secret = "26291a3ff5e6cc6c3e7bf92d1e95b0cb"
    
    ///获取oauth授权的登陆界面地址
    func oAuthLoginURL() -> NSURL {
    
        let URLString = oAuth2URL + "?" + "client_id=" + client_id + "&" + "redirect_uri=" + redirect_uri
        return NSURL(string: URLString)!
    }
    
    /**
    获取AccssesToken
    */
    func laodAccessToken(code: String, assTokenFinished: (reponse: [String : AnyObject]? , eror:NSError? ) -> () ) {
        //请求地址
        let urlString = "https://api.weibo.com/oauth2/access_token"
        
        //请求参数
        let parametes = [
            
            "client_id"     : client_id ,
            "client_secret" : client_secret,
            "grant_type"    : "authorization_code",
            "code"          : code,
            "redirect_uri"  : redirect_uri
        ]
        
        //post请求向新浪发送
        afnManger.POST(urlString, parameters: parametes, progress: nil, success: {
            (_, response) -> Void in
            
            //将response转成字典
            let dict = response as? [String : AnyObject]
            //调用在viewModel的闭包 把 reponse 转为模型传过去
            assTokenFinished(reponse: dict, eror: nil)
            
            }){ (_, error) -> Void in
                
                assTokenFinished(reponse: nil, eror: error)
        }
    }
    
    /**
     加载用户资料
     
     - parameter finished: 完成回调
     */
    func loadUserInfo(finished: finishedCallBack) {
        
        guard let uid = SWUserAccountViewModel.sharedInstance.userAccount?.uid else {
            let error = SWNetWorkToolError.UidEmpty.error()
            //获取UID失败
            finished(result: nil, error: error)
            return
        }
        //请求地址
        let urlString = "https://api.weibo.com/2/users/show.json"
        //请求参数
        let parameters = ["uid" : uid]
        
        requestGET(urlString, parameters: parameters, finished: finished)
        
    }
    
    /**
     加载微博数据
    */
    func loadStatus(since_id: Int , max_id: Int , finished: finishedCallBack) {
        
        let deBug = false
        
        if deBug {
            
            loadLocaStatus(finished)
            return
        }
        
        // url
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        // 参数
        var parameters = [String : AnyObject]()
        
        if since_id > 0 { //获取最新微博的请求参数
            
            parameters["since_id"] = since_id
            
        }else if max_id > 0 { //获取之前的微博的请求参数
            
            parameters["max_id"] = max_id - 1
        }
        
        //请求数据
        requestGET(urlString, parameters: parameters, finished: finished)
        
    }
    
    //本地測試數據
    private func loadLocaStatus(finished: finishedCallBack) {
        
        let path = NSBundle.mainBundle().pathForResource("statuses.json", ofType: nil)!
        
        let data = NSData(contentsOfFile: path)!
        
        do { //json會拋出錯誤
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(rawValue: 0))
            
            finished(result: json as? [String : AnyObject], error: nil)
        
        }catch { //拋出錯誤時來這
        
            print("讀取json出現異常")
        }
    
    
    }
    
    ///完成回调闭包
    typealias finishedCallBack = (result: [String : AnyObject]?, error: NSError?) -> ()
    
    ///封装请求数据方法
    private func requestGET(urlString: String, var parameters: [String : AnyObject]?,finished: finishedCallBack) {
        //守卫
        guard let access_token = SWUserAccountViewModel.sharedInstance.userAccount?.access_token else {
            //当assess_token没有值的时候进来
            finished(result: nil, error: SWNetWorkToolError.AccssesTokenEmpty.error())
            return
        }
        
        //当没有参数传入时 创建参数字典
        if parameters == nil {
            parameters = [String : AnyObject]()
        }
        //拼接参数 access_token
        parameters!["access_token"] = access_token
        
        //发送请求
        afnManger.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            //成功获得字典
            finished(result: result as? [String : AnyObject], error: nil)
            
            }) { (_, error) -> Void in
                //失败
                finished(result: nil, error: error)
        }
    }
    
    
    
    
}
